<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="Plus" @click="addTrademark">
        添加品牌
      </el-button>

      <!-- 表格组件 -->
      <el-table
        v-loading="loading"
        class="trademark_table"
        :data="trademarkArr"
        :border="true"
      >
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column
          prop="tmName"
          label="品牌名称"
          width="350"
          align="center"
        />
        <el-table-column label="品牌LOGO" width="350" align="center">
          <template #="{ row }">
            <div class="trademark_table-image">
              <img :src="row.logoUrl" alt="未有图片" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row }">
            <el-button
              type="primary"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              @confirm="deleteTrademar(row.id)"
              :title="`确定删除${row.tmName}?`"
              icon="Delete"
              icon-color="rgb(244,108,108)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 
      pagination:
        v-model:current-page:设置分页器当前页码
        v-model:page-size:设置每一个展示数据条数
        :page-sizes:用于设置下拉菜单数据
        :background:设置分页器按钮的背景颜色
        layout:可以设置分页器六个子组件布局调整
      -->
      <el-pagination
        @size-change="sizeChange"
        @current-change="getHasTrademark"
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="false"
        layout=", prev, pager, next, jumper,->, sizes,total"
        :total="count"
      />
    </el-card>

    <!-- 对话框组件:在添加品牌与修改已有品牌的业务时候使用结构 
      v-model:这个属性控制对话框显示与隐藏
      title:设置对话框左上角标题
    -->
    <el-dialog
      class="trademark_dialog"
      v-model="dialogFormVisible"
      :title="dialogTitle + '品牌'"
      width="650px"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item prop="tmName" label="品牌名称" label-width="96px">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请你输入品牌名称"
          />
        </el-form-item>
        <el-form-item prop="logoUrl" label="品牌LOGO" label-width="96px">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger" size="default" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademar,
  reqDeleteTrademar,
} from "@/api/product/trademark";
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from "@/api/product/trademark/type";
import { ElMessage, type UploadProps } from "element-plus";
// 当前页码
let pageNo = ref<number>(1);
// 每一页展示多少条数据
let limit = ref<number>(5);
// 存储已有品牌数据总数
let count = ref<number>(0);
// 存储已有品牌的数据
let trademarkArr = ref<Records>([]);
// 对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//  对话框title
let dialogTitle = ref<string>("");
// 获取el-from组件实例
let formRef = ref();
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});

// 表单自定义校验方法
const validatorTmName = (_: any, value: any, callBack: any) => {
  // 自定义校验规则
  if (value.trim().length >= 2) {
    callBack();
  } else {
    callBack(new Error("品牌名称必须大于大于两位"));
  }
};

// 表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, message: "请上传品牌图片" }],
};

// 获取品牌数据
const getHasTrademark = async (pager = 1) => {
  loading.value = true;
  // 当前页码
  pageNo.value = pager;
  let {
    code,
    data: { total, records },
  }: TradeMarkResponseData = await reqHasTrademark(pageNo.value, limit.value);
  if (code === 200) {
    count.value = total;
    trademarkArr.value = records;
  }
  loading.value = false;
};

// 当下拉菜单发生变化的时候触发方法(分页器组件的下拉菜单)
const sizeChange = () => {
  getHasTrademark();
};

// 添加品牌按钮
const addTrademark = () => {
  // 第一种写法
  formRef.value?.clearValidate(["tmName", "logoUrl"]);
  // 第二种写法
  // nextTick(() => {
  //   formRef.value.clearValidate(["tmName", "logoUrl"]);
  // });
  dialogTitle.value = "添加";
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  dialogFormVisible.value = true;
};
// 修改品牌按钮
const updateTrademark = (row: TradeMark) => {
  formRef.value?.clearValidate(["tmName", "logoUrl"]);
  dialogTitle.value = "修改";
  Object.assign(trademarkParams, row);
  dialogFormVisible.value = true;
};
// 删除品牌按钮
const deleteTrademar = async (row: number) => {
  let result = await reqDeleteTrademar(row);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除品牌成功",
    });
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    );
  } else {
    ElMessage({
      type: "error",
      message: "删除品牌失败",
    });
  }
};
// 对话框取消按钮
const cancel = () => {
  dialogFormVisible.value = false;
};
// 对话框确定按钮
const confirm = async () => {
  // validate:对整个表单的内容进行验证。 接收一个回调函数，或返回 Promise
  await formRef.value.validate(async (valid: any) => {
    if (valid) {
      let result: any = await reqAddOrUpdateTrademar(trademarkParams);
      if (result.code === 200) {
        ElMessage({
          type: "success",
          message: dialogTitle.value + "品牌成功",
        });
        getHasTrademark(dialogTitle.value === "修改" ? pageNo.value : 1);
      } else {
        ElMessage({
          type: "error",
          message: dialogTitle.value + "品牌失败",
        });
      }
      dialogFormVisible.value = false;
    }
  });
};
// 上传图片之前做什么事
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "文件上大小必须小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "文件上传格式必须是PNG、JPEG、GIF",
    });
    return false;
  }
};
// 上传图片成功的构子函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  // response:为上传图片，请求服务器返回的数据
  trademarkParams.logoUrl = response.data;
  // 图片上传成功，清除掉对应图片校验结果
  formRef.value.clearValidate("logoUrl");
};
onMounted(() => {
  getHasTrademark();
});
</script>
<style scoped lang="scss">
.trademark_table {
  width: 100%;
  margin: 16px 0;

  .trademark_table-image {
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;

    img {
      width: 100px;
      object-fit: cover;
    }
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

@media screen and (max-width: 768px) {
  :deep(.trademark_dialog) {
    width: 450px !important;
  }
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  height: 178px;
  width: 178px;
}

.avatar-uploader .el-upload > img {
  width: 100%;
  height: auto !important;
  object-fit: cover;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
